#!/usr/bin/env python3

import argparse
from pathlib import Path
import base64
import hmac
import hashlib


def hash_hostname(hostname: str, salt_b64: str) -> str:
    salt = base64.b64decode(salt_b64)
    mac = hmac.new(salt, hostname.encode('utf-8'), hashlib.sha1)
    hashed = base64.b64encode(mac.digest()).decode('utf-8')
    return hashed


def parse_known_hosts_line(line: str):
    parts = line.strip().split()
    if len(parts) < 3:
        return None, None, None
    hosts = parts[0]
    keytype = parts[1]
    key = parts[2]
    return hosts, keytype, key


def match_hashed_host(hosts_field: str, hostname: str) -> bool:
    if not hosts_field.startswith('|1|'):
        return False
    try:
        _, salt_b64, hashed_b64 = hosts_field.split('|')[1:4]
    except ValueError:
        return False
    computed_hash = hash_hostname(hostname, salt_b64)
    return computed_hash == hashed_b64


def main():
    parser = argparse.ArgumentParser(
        description="Check if a hashed hostname exists in known_hosts file.")
    parser.add_argument(
        "-f", "--file",
        type=Path,
        default=Path("~/.ssh/known_hosts").expanduser(),
        help="Path to known_hosts file (default: ~/.ssh/known_hosts)"
    )
    parser.add_argument(
        "hostname",
        type=str,
        help="Hostname to check"
    )
    args = parser.parse_args()

    with args.file.open('r') as f:
        for line in f:
            hosts, keytype, key = parse_known_hosts_line(line)
            if not hosts:
                continue
            if match_hashed_host(hosts, args.hostname):
                print(f"Found matching hashed host: {line.strip()}")


if __name__ == "__main__":
    main()
